'use strict';

    angular.module('app').controller('userUpdateController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster',
        function($scope, $rootScope, $state, $timeout, toaster) {
    	
    	$scope.record = {
    		deptId:$state.params.regionId,
    		regionId:$state.params.regionId,
    		enable:1,
    		id:$state.params.id
    	};
    	$scope.regionName = $state.params.regionName;
    	$scope.stateRegionId = $state.params.regionId;
    	$scope.stateRegionName = $state.params.regionName;
        if($state.includes('**.user.update')){
            $scope.title="编辑操作员";
            $scope.NoEdit = true;
            $scope.loading = true;
            $scope.reset = false;//修改不允许重置
            var id = $state.params.id;
            activate(id);
        }else if($state.includes('**.user.create')){
            $scope.title="新增操作员";
            $scope.NoEdit = false;
            $scope.reset = true;//新增时可以重置
        }
		//重置表单
		$scope.resetFrom = function(){
		   $scope.record = {
	    		deptId:state.params.regionId,
	    		regionId:$state.params.regionId,
	    		enable:1,
	    		id:$state.params.id
    		}
		}
        //初始化验证
        validate();
        $scope.submit= function(){
        	if($scope.record.id != null){//id非空代表着是修改
        		updateUser();
        	}else{//新增
        		saveData();
        	}
        };
        //新增操作员
        function saveData(){
            var m = $scope.record;
            if(m){
                $scope.isDisabled = true;//提交disabled
                $.ajax({
                	type: 'POST',
    				url : '/user/create/opuser',
    	            dataType: 'json',
    				contentType:'application/json;charset=UTF-8',
    				data: angular.toJson(m)
    			}).then(function(result){
    				if(result.httpCode ==200){//成功
	                	toaster.clear('*');
	                    toaster.pop('success', '', "保存成功");
	                    $timeout(function(){
	                        $state.go('main.sys.user.list', $state.params);
	                    },2000);
	                }else{
	                    toaster.clear('*');
	                    toaster.pop('error', '', result.msg);
	                    $scope.isDisabled = false;
	                }
                	$scope.loading = false;
    			});
            }
        }
        //修改操作员
        function updateUser(){
            var m = $scope.record;
            if(m){
                $scope.isDisabled = true;//提交disabled
                $.ajax({
                	type: 'POST',
    				url : '/user/update/updateOpUser',
    	            dataType: 'json',
    				contentType:'application/json;charset=UTF-8',
    				data: angular.toJson(m)
    			}).then(function(result){
    				if(result.httpCode ==200){//成功
	                	toaster.clear('*');
	                    toaster.pop('success', '', "保存成功");
	                    $timeout(function(){
	                        $state.go('main.sys.user.list', $state.params);
	                    },2000);
	                }else{
	                    toaster.clear('*');
	                    toaster.pop('error', '', result.msg);
	                    $scope.isDisabled = false;
	                }
	                $scope.loading = false;
    			});
            }
        }

        // 初始化页面
        function activate(id) {
	        $scope.loading = true;
        	$.ajax({
        		type: 'PUT',
				url : '/user/read/detail',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				data: angular.toJson({'id': id})
			}).then(function(result) {
		        $scope.loading = false;
                console.log(result);
				if (result.httpCode == 200) {
					console.log(result.data.roleId);
					$scope.record = result.data;
					$scope.record.beginTime = $scope.record.beginTime.substr(0,10);//去掉时分秒
					$scope.record.endTime = $scope.record.endTime.substr(0,10);//去掉时分秒
					$scope.record.password = '';
					$scope.regionName = result.data.regionName;
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
        }

        //表单验证
        function validate(userId){
            //notEqual 规则
            $.validator.addMethod('notEqual', function(value, ele){
                return value != this.settings.rules[ele.name].notEqual;
            });
            jQuery('form').validate({
                rules: {
                    account: {
                        required: true,
                        stringCheck:[],
                        maxLengthB:[10]//,
                        //isExist:['/user/checkName',userId]
                    },
                    userName: {
                        required: true,
                        maxlength: 20
                    },
                    phone: {
                        required: true,
                        maxlength: 11,
                        isPhone:[]
                    },
                    confirmPassword:{
                       // required: true,
                        maxlength: 16,
                        equalTo: "#password"
                    },
                    roleId:{
                    	required: true
                    }
                    ,
                    beginTime:{
                        required: true
                    },
                    endTime:{
                        required: true
                    },
                    projeck:{
                        required:true
                    }
                },
                messages: {
                    account: {
                        required: '请输入操作员账号',
                        maxLengthB:"操作员工号不得超过{0}个字符",
                        isExist:"该操作员工号已存在"
                    },
                    userName: {
                        required: '请输入操作员昵称',
                        maxlength: '操作员名称不可大于20位'
                    },
                    phone: {
                        required: '请输入手机号码',
                        maxlength: '手机号码不可大于11位'
                    },
                    confirmPassword:{
                        //required: '请填写确认密码',
                        maxlength: '密码长度不可大于16位',
                        equalTo: '两次输入的密码不相符'
                    },
                    roleId:{
                    	required:'请选择操作员角色'
                    },
                    beginTime:{
                        required:'请选择开始时间'
                    }
                    ,
                    endTime:{
                        required:'请选择结束时间'
                    },
                    projeck:{
                        required:'请选择项目类型'
                    }
                },
                submitHandler: function() {
                    $scope.submit();
                }
            });
        }
        
        $scope.loadUserType = function () {
    		$scope.param = {};
    		$scope.param.key='USERTYPE';
    		$.ajax({
				type: 'PUT',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				url : '/dic/queryDicByType',
				data: angular.toJson($scope.param)
			}).then(function(result) {
				if (result.httpCode == 200) {
					$scope.userTypes = result.data;
					$scope.$apply();
				} 
				
			});
    	}
    	
    	$scope.loadUserType();
    	
        $scope.loadRole = function () {
    		$scope.param = {};
    		$.ajax({
				type: 'PUT',
	            dataType: 'json',
				contentType:'application/json;charset=UTF-8',
				url : '/role/queryRoles',
				data: angular.toJson($scope.param)
			}).then(function(result) {
				if (result.httpCode == 200) {
					$scope.roles = result.data;
//					for(var i=0;i<result.data.length;i++){
//						console.log(result.data[i].id);
//					}
					$scope.$apply();
				} 
				
			});
    	}

        $scope.loadRole();

      //日期控件
        $scope.dateOptions = {
             startingDay: 1,
             class: 'datepicker'
        };
         $scope.openDatepicker = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if(i==1){
            	$scope.beginTime = true;
            }else if(i==2){
            	$scope.endTime = true;
            }
         }

        // //在Controller中绑定选择控件
        // var datepicker1 = $('#datetimepicker1').datetimepicker({
        //  format: 'YYYY-MM-DD',
        //  locale: moment.locale('zh-CN')
        // }).on('dp.change', function (e) {
        //  var result = new moment(e.date).format('YYYY-MM-DD');
        //  $scope.dateOne = result;
        //  $scope.$apply();
        // });
        
        //所属项目
        $scope.projeck = function(){
            $.ajax({
                type: 'PUT',
                dataType: 'json',
                contentType:'application/json;charset=UTF-8',
                url : '/user/prolist',
                data: angular.toJson($scope.param)
            }).then(function(result) {
                if (result.httpCode == 200) {
                    console.log(result);
                    $scope.projeck = result.data;
                    $scope.$apply();
                } 
                
            });
        }
        $scope.projeck();

    }]);